package com.qin.mall.controller;

import com.qin.mall.common.api.CommonResult;
import com.qin.mall.common.constant.AuthConstant;
import com.qin.mall.domain.Oauth2TokenDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 自定义授权Oauth2
 * @author Leisure
 * create 2022 2022/11/16 10:03
 **/
//授权认证中心
@RestController
@RequestMapping("/oauth")
public class AuthController {
    
    @Autowired
    private TokenEndpoint tokenEndpoint;
    
    @PostMapping("/token")
    public CommonResult<Oauth2TokenDto> postAccessToken(
                            HttpServletRequest request,
                            @RequestParam String grant_type, //授权模式,
                            @RequestParam String client_id, //Oauth2客户端ID
                            @RequestParam String client_secret, //Oauth2客户端秘钥
                            @RequestParam(required = false) String refresh_token, //刷新token
                            @RequestParam(required = false) String username, //登录用户名
                            @RequestParam(required = false) String password)
                            throws HttpRequestMethodNotSupportedException {
        HashMap<String, String> parameters = new HashMap<>();
        parameters.put("grant_type",grant_type);
        parameters.put("client_id",client_id);
        parameters.put("client_secret",client_secret);
        parameters.putIfAbsent("refresh_token",refresh_token);
        parameters.putIfAbsent("username",username);
        parameters.putIfAbsent("password",password);
        
        // 调用oauth原生的授权换取token
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(request.getUserPrincipal(), parameters).getBody();
        Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead(AuthConstant.JWT_TOKEN_PREFIX).build();
        //返回token
        return CommonResult.success(oauth2TokenDto);
    }
}
